package cn.tannn.ops.customer.service.impl;


import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.exception.built.UserException;
import cn.tannn.jdevelops.jpa.service.J2ServiceImpl;
import cn.tannn.ops.customer.constant.RoleDef;
import cn.tannn.ops.customer.controller.dto.*;
import cn.tannn.ops.customer.dao.CustomerDao;
import cn.tannn.ops.customer.dao.RoleCustomerDao;
import cn.tannn.ops.customer.entity.Customer;
import cn.tannn.ops.customer.service.CustomerService;
import cn.tannn.ops.logs.controller.dto.LoginLogRecord;
import cn.tannn.ops.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static cn.tannn.jdevelops.utils.jwt.exception.UserCode.USER_EXIST_ERROR;
import static cn.tannn.jdevelops.utils.jwt.exception.UserCode.USER_PASSWORD_ERROR;
import static cn.tannn.ops.customer.entity.Customer.getMd5Password;



/**
 * 系统用户(管理者)
 *
 * @author tnnn
 * @version V1.0
 * @date 2023-10-25
 */
@Slf4j
@Service
public class CustomerServiceImpl extends J2ServiceImpl<CustomerDao, Customer, Long> implements CustomerService {

    private final RoleCustomerDao roleCustomerDao;


    public CustomerServiceImpl(RoleCustomerDao roleCustomerDao) {
        super(Customer.class);
        this.roleCustomerDao = roleCustomerDao;
    }

    @Override
    public Customer authenticateUser(LoginPassword login
            , LoginAttach attach) {
        Optional<Customer> byLoginName = getJpaBasicsDao().findByLoginName(login.getLoginName());
        LoginLogRecord logRecord = new LoginLogRecord();
        logRecord.setType(attach.getLoginType().getDescription());
        if (!byLoginName.isPresent()) {
            logRecord.setRequest(attach.getRequest());
            Customer customer = new Customer();
            customer.setLoginName(login.getLoginName());
            customer.setName("");
            logRecord.setCustomer(customer);
            logRecord.setStatus(0);
            logRecord.setDescription("用户不存在");
            LogUtil.loginLog(logRecord);
            throw new UserException(USER_EXIST_ERROR);
        }
        Customer authUser = byLoginName.get();
        // 密码为空不允许登录
        if (StringUtils.isBlank(login.getPassword())) {
            logRecord.setRequest(attach.getRequest());
            logRecord.setCustomer(authUser);
            logRecord.setStatus(0);
            logRecord.setDescription(USER_PASSWORD_ERROR.getMessage());
            LogUtil.loginLog(logRecord);
            throw new UserException(USER_PASSWORD_ERROR);
        }
        try {
            // 验证状态
            authUser.verifyStatus();
            // 验证 密码
            authUser.verifyUserPassMd5(login.getPassword());
        } catch (UserException user) {
            logRecord.setRequest(attach.getRequest());
            logRecord.setCustomer(authUser);
            logRecord.setStatus(0);
            logRecord.setDescription(user.getMessage());
            LogUtil.loginLog(logRecord);
            throw user;
        }
        return authUser;
    }

    @Override
    public boolean registerUser(CustomerRegister register, CustomerRegisterAttach attach) {
        if (userExist(register.getLoginName())) {
            throw new BusinessException("用户已存在，请重新注册");
        }
        Customer to = register.to(Customer.class);
        if (StringUtils.isNotBlank(register.getPassword())) {
            to.setPassword(getMd5Password(register.getLoginName(), register.getPassword()));
        } else {
            throw new UserException("注册用户密码不允许为空");
        }
        to.setStatus(attach.getStatus().getStatus());
        to.setStatusMark(attach.getStatusMark());
        to.setAuditStatus(attach.getAuditStatus());
        to.setRemark(attach.getRemark());
        to.setNickname(register.getName());
        getJpaBasicsDao().save(to);
        return true;
    }

    @Override
    public void editPassword(String loginName, String newPassword) {
        Optional<Customer> byLoginName = getJpaBasicsDao().findByLoginName(loginName);
        byLoginName.ifPresent(entity -> {
            String md5Password = getMd5Password(loginName, newPassword);
            entity.setPassword(md5Password);
            getJpaBasicsDao().save(entity);
        });
    }


    @Override
    public Optional<Customer> findByLoginName(String loginName) {
        return getJpaBasicsDao().findByLoginName(loginName);
    }

    @Override
    public List<Customer> findByIds(List<Long> ids) {
        return getJpaBasicsDao().findByIdIn(ids);
    }


    @Override
    public boolean userExist(String loginName) {
        Optional<Customer> byLoginName = getJpaBasicsDao().findByLoginName(loginName);
        return byLoginName.isPresent();
    }

    @Override
    public boolean verifyLoginAdmin(String loginName) {
        try {
            // todo 后期这里用 缓存
            Optional<Customer> user = getJpaBasicsDao()
                    .findByLoginName(loginName);
            if(user.isPresent()){
                List<String> roles = roleCustomerDao.findRoleCodeByUserId(user.get().getId());
                return roles.contains(RoleDef.USER_ADMIN);
            }
        } catch (Exception e) {
            log.warn("验证当前登录用户是非为超级管理员失败", e);
        }
        return false;
    }


    @Override
    public void settingStatus(CustomerSettingStatus status) {
        getJpaBasicsDao().updateStatus(status);
    }

    @Override
    public Optional<Customer> findById(Long id) {
        return getJpaBasicsDao().findById(id);
    }





}
